﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ChuanYe.CountyFireManagement.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Hosting;

namespace ChuanYe.CountyFireManagement.Api.Controllers
{
    /// <summary>
    /// 文件上传
    /// </summary>
    [Route("api/[controller]/[action]")]
    [DisableRequestSizeLimit]
    public class UploadController : ControllerBase
    {
        /// <summary>
        /// 
        /// </summary>
        public IHostingEnvironment env;

        /// <summary>
        /// /
        /// </summary>
        /// <param name="_env"></param>
        public UploadController(IHostingEnvironment _env)
        {
            env = _env;
        }

        /// <summary>
        /// 使用表单提交
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultDto<string>> Post()
        {
            ResultDto<string> result = new ResultDto<string>();

            try
            {
                var files = Request.Form.Files;
                if (files.Count > 0)
                {
                    var file = files[0];
                    var path = env.ContentRootPath + @"/Upload/";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    var prefixName = DateTime.Now.ToString("yyyyMMddHHmmsss");
                    var fileName = $"CY_{prefixName}_{file.FileName}";
                    string snPath = $"{path + fileName}";
                    using var stream = new FileStream(snPath, FileMode.Create);
                    await file.CopyToAsync(stream);
                    result.FirstParam = @"/Upload/"+fileName;
                }
                else
                {
                    result.Message = "File Is Null";
                    result.Status = -1;
                }
            }
            catch (Exception ex)
            {
                result.Status = 500;
                result.Message = "/Upload/Post Error";
                LogHelper.Error(result.Message,ex);
            }
            return result;
        }
    }
}